


package ciicos.controller;

import ciicos.service.LineLineService;
import ciicos.service.LinePlaceService;
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import ciicos.annotation.JnpfField;
import ciicos.base.ActionResult;
import ciicos.base.vo.PageListVO;
import ciicos.base.vo.PaginationVO;
import ciicos.base.UserInfo;
import ciicos.base.vo.DownloadVO;
import ciicos.config.ConfigValueUtil;
import ciicos.exception.DataException;
import ciicos.onlinedev.model.OnlineImport.ExcelImFieldModel;
import ciicos.onlinedev.model.OnlineImport.ExcelImportModel;
import ciicos.onlinedev.model.OnlineImport.VisualImportModel;
import ciicos.permission.entity.UserEntity;
import org.springframework.transaction.annotation.Transactional;
import ciicos.base.entity.ProvinceEntity;
import ciicos.model.lineproject.*;
import ciicos.model.lineproject.LineProjectPagination;
import ciicos.entity.*;
import ciicos.util.*;
import ciicos.base.util.*;
import ciicos.base.vo.ListVO;
import ciicos.util.context.SpringContext;
import cn.hutool.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;
import lombok.Cleanup;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import ciicos.entity.LineProjectEntity;
import ciicos.service.LineProjectService;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import ciicos.util.GeneraterSwapUtil;

import java.util.stream.Collectors;
import java.util.*;

import cn.xuyanwu.spring.file.storage.FileInfo;


/**
 * 作业工程管理
 *
 * @版本： V3.2.0
 * @版权：
 * @作者： 企业研发中心
 * @日期： 2025-10-06
 */
@Slf4j
@RestController
@Api(tags = "作业工程管理", value = "line")
@RequestMapping("/api/line/LineProject")
public class LineProjectController {

    @Autowired
    private GeneraterSwapUtil generaterSwapUtil;


    @Autowired
    private UserProvider userProvider;


    @Autowired
    private LineProjectService lineProjectService;

    @Autowired
    private LineLineService lineLineService;

    @Autowired
    private LinePlaceService linePlaceService;

    /**
     * 列表
     *
     * @param lineProjectPagination
     * @return
     */
    @ApiOperation("获取列表")
    @PostMapping("/getList")
    public ActionResult list(@RequestBody LineProjectPagination lineProjectPagination) throws IOException {
        //树形判断是否有参数，有参数不造树
        PageListVO vo = new PageListVO();

        //1.获取主表数据
        List<LineProjectEntity> list = lineProjectService.getList(lineProjectPagination);
        if(list==null || list.size()==0){
            PaginationVO page = JsonUtil.getJsonToBean(lineProjectPagination, PaginationVO.class);
            vo.setPagination(page);
            vo.setList(new ArrayList());
            return ActionResult.success(vo);
        }

        Map<String,String> mapList1 =
                AutoCodeUtil.getMapByCodeList(lineLineService,
                        list.stream().filter(t->StringUtil.equals(t.getLineplacetype(),"1")).map(LineProjectEntity::getLineplaceid).collect(Collectors.toList()),
                        LineLineEntity::getCode,LineLineEntity::getName,true);
        Map<String,String> mapList2 =
                AutoCodeUtil.getMapByCodeList(linePlaceService,
                        list.stream().filter(t->StringUtil.equals(t.getLineplacetype(),"2")).map(LineProjectEntity::getLineplaceid).collect(Collectors.toList()),
                        LinePlaceEntity::getCode,LinePlaceEntity::getName,true);

        List<LineProjectListVO> listVO = JsonUtil.getJsonToList(list, LineProjectListVO.class);
        for (LineProjectListVO lineProjectVO : listVO) {
            lineProjectVO.setLineplacetype_name(lineProjectVO.getLineplacetype());
            if (lineProjectVO.getLineplacetype().equals("1")) {
                lineProjectVO.setLineplaceid_name(mapList1.get(lineProjectVO.getLineplaceid()));
            } else if (lineProjectVO.getLineplacetype().equals("2")) {
                lineProjectVO.setLineplaceid_name(mapList2.get(lineProjectVO.getLineplaceid()));
            }
            lineProjectVO.setName_name(lineProjectVO.getName());
            lineProjectVO.setType_name(lineProjectVO.getType());
            lineProjectVO.setStarttime_name(lineProjectVO.getStarttime() != null ?
                    new Date(lineProjectVO.getStarttime()) : null);
            lineProjectVO.setEndtime_name(lineProjectVO.getEndtime() != null ?
                    new Date(lineProjectVO.getEndtime()) : null);
            lineProjectVO.setExecutor_name(lineProjectVO.getExecutor());
            lineProjectVO.setMasteruserid_name(lineProjectVO.getMasteruserid());
            lineProjectVO.setContactuserid_name(generaterSwapUtil.userSelectValues(lineProjectVO.getContactuserid()));
            lineProjectVO.setStatus_name(lineProjectVO.getStatus());
            lineProjectVO.setContent_name(lineProjectVO.getContent());
            //子表数据转换
        }


        vo.setList(listVO);
        PaginationVO page = JsonUtil.getJsonToBean(lineProjectPagination, PaginationVO.class);
        vo.setPagination(page);
        return ActionResult.success(vo);

    }

    /**
     * 创建
     *
     * @param lineProjectForm
     * @return
     */
    @PostMapping
    @Transactional
    @ApiOperation("创建")
    public ActionResult create(@RequestBody @Valid LineProjectForm lineProjectForm) throws DataException {
        String b = lineProjectService.checkForm(lineProjectForm, 0);
        if (StringUtil.isNotEmpty(b)) {
            return ActionResult.fail(b + "不能重复");
        }
        String mainId = RandomUtil.uuId();

        UserInfo userInfo = userProvider.get();
        UserEntity userEntity = generaterSwapUtil.getUser(userInfo.getUserId());
        LineProjectEntity entity = JsonUtil.getJsonToBean(lineProjectForm, LineProjectEntity.class);
        entity.setId(mainId);
        lineProjectService.save(entity);


        return ActionResult.success("创建成功");
    }


    /**
     * 信息
     *
     * @param id
     * @return
     */
    @ApiOperation("信息")
    @GetMapping("/{id}")
    public ActionResult<LineProjectInfoVO> info(@PathVariable("id") String id) {
        LineProjectEntity entity = lineProjectService.getInfo(id);
        LineProjectInfoVO vo = JsonUtil.getJsonToBean(entity, LineProjectInfoVO.class);

        //子表
        //副表
        return ActionResult.success(vo);
    }

    /**
     * 表单信息(详情页)
     *
     * @param id
     * @return
     */
    @ApiOperation("表单信息(详情页)")
    @GetMapping("/detail/{id}")
    public ActionResult<LineProjectInfoVO> detailInfo(@PathVariable("id") String id) {
        ActionResult info = info(id);
        Map<String, Object> dataMap = JsonUtil.entityToMap(info.getData());
        LineProjectEntity entity = lineProjectService.getInfo(id);
        LineProjectInfoVO vo = JsonUtil.getJsonToBean(entity, LineProjectInfoVO.class);

        //子表数据转换

        //附表数据转换

//添加到详情表单对象中
        vo.setLineplacetype(vo.getLineplacetype());

        Map<String, Object> lineplaceidMap = new HashMap<>();
        vo.setLineplaceid(generaterSwapUtil.getPopupSelectValue("743867011288793541", "F_Code", "F_Code", vo.getLineplaceid(), lineplaceidMap, "[]", -1, dataMap));

        vo.setName(vo.getName());

        vo.setType(vo.getType());

        vo.setStarttime(vo.getStarttime());

        vo.setEndtime(vo.getEndtime());

        vo.setExecutor(vo.getExecutor());

        vo.setMasteruserid(vo.getMasteruserid());

        vo.setContactuserid(generaterSwapUtil.userSelectValues(vo.getContactuserid()));

        vo.setStatus(vo.getStatus());

        vo.setContent(vo.getContent());


        return ActionResult.success(vo);
    }


    /**
     * 更新
     *
     * @param id
     * @param lineProjectForm
     * @return
     */
    @PutMapping("/{id}")
    @Transactional
    @ApiOperation("更新")
    public ActionResult update(@PathVariable("id") String id, @RequestBody @Valid LineProjectForm lineProjectForm) throws DataException {
        String b = lineProjectService.checkForm(lineProjectForm, 1);
        if (StringUtil.isNotEmpty(b)) {
            return ActionResult.fail(b + "不能重复");
        }
        UserInfo userInfo = userProvider.get();
        LineProjectEntity entity = lineProjectService.getInfo(id);
        if (entity != null) {
            LineProjectEntity subentity = JsonUtil.getJsonToBean(lineProjectForm, LineProjectEntity.class);
            boolean b1 = lineProjectService.updateById(subentity);
            if (!b1) {
                return ActionResult.fail("当前表单原数据已被调整，请重新进入该页面编辑并提交数据");
            }
            return ActionResult.success("更新成功");
        } else {
            return ActionResult.fail("更新失败，数据不存在");
        }
    }


    /**
     * 删除
     *
     * @param id
     * @return
     */
    @ApiOperation("删除")
    @DeleteMapping("/{id}")
    @Transactional
    public ActionResult delete(@PathVariable("id") String id) {
        LineProjectEntity entity = lineProjectService.getInfo(id);
        if (entity != null) {
            lineProjectService.delete(entity);
        }
        return ActionResult.success("删除成功");
    }


}
